package com.baizhi.realm;

import com.baizhi.dao.CmfzAdminDao;
import com.baizhi.entity.CmfzAdmin;
import com.baizhi.service.CmfzRoleService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

public class AuthorRealm extends AuthorizingRealm {
    @Autowired
    private CmfzAdminDao cmfzAdminDao;
    @Autowired
    private CmfzRoleService cmfzRoleService;
    /**
     * 获取授权信息
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
//        1.获取用户名 getPrimaryPrincipal(主身份信息)
        String username = (String) principals.getPrimaryPrincipal();
        System.out.println(username);
//        2.根据用户名获取角色信息和权限信息
        Set<String> roles = cmfzRoleService.getAllRolesByUsername(username);
        Set<String> permissions = cmfzRoleService.getAllPermissionsByUsername(username);

//        3.封装info
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setRoles(roles);
        info.setStringPermissions(permissions);

        return info;
    }

    /**
     * 获取认证信息
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
//        1.获取用户名
        UsernamePasswordToken passwordToken = (UsernamePasswordToken) token;
        String username = passwordToken.getUsername();

//        2.根据用户名查询数据库
        CmfzAdmin cmfzAdmin = cmfzAdminDao.selectOne(new QueryWrapper<CmfzAdmin>().eq("username", username));

//        3.如果不为null 返回info
        if (cmfzAdmin != null) {
            System.out.println();
            return new SimpleAuthenticationInfo(cmfzAdmin.getUsername(),cmfzAdmin.getPassword(),this.getName());
        }
        return null;
    }
}
